package com.ea.eadp.nexus.test.common;

import org.apache.xerces.dom.DeferredElementImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;


/**
 * Created with IntelliJ IDEA.
 * User: WenjieLu
 * Date: 3/6/13
 * Time: 11:40 AM
 * To change this template use File | Settings | File Templates.
 */
public class XMLInfo {

    private NodeList nodes = null;

    public void init(String folder, String langs) throws Exception {
        InputStream xmlFile = XMLInfo.class.getResourceAsStream("/localization/" + folder + "/messages_" + langs + ".xml");
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(false);
            dbf.setFeature("http://xml.org/sax/features/namespaces", false);
            dbf.setFeature("http://xml.org/sax/features/validation", false);
            dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

            DocumentBuilder db = dbf.newDocumentBuilder();

            Document doc = db.parse(xmlFile);
            Element elmtInfo = doc.getDocumentElement();
            nodes = elmtInfo.getElementsByTagName("entry");
        } finally {
            xmlFile.close();
        }
    }

    public String getKey(String key) throws Exception {
        for (int i = 0; i <= nodes.getLength() - 1; i++) {
            Element element = (Element) nodes.item(i);
            if (element.getAttribute("key").equals(key)) {
                return ((DeferredElementImpl) element).item(0).getNodeValue().trim();
            }
        }
        return null;
    }
}
